/*
 * Created by Asnull.
 * Website:https://lipux.cn/
 * Date:2023-4-1
 */

const mysql = require('mysql');
const fs = require("fs");
const dayjs = require('dayjs');
const axios = require('axios');
const qs = require('qs');
const config = require('./config');

// 连接到数据库
const database = mysql.createPool(config.mysql_config);

// 登录
module.exports.login = (req, res) => {
    let { uid, password } = req.body;
    let sql = 'select * from user where uid=? and password=?';
    database.query(sql, [uid, password], (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: '账号或密码不存在！'
        })
        if (result.length >= 1) {
            res.send({
                code: 200,
                uid: result[0].uid,
                name: result[0].name,
                msg: '登录成功！'
            })
        } else {
            res.send({
                code: 400,
                msg: '账号或密码不存在！'
            })
        }

    })
}

// 获取对话列表
module.exports.getChatList = (req, res) => {
    let { uid } = req.body;
    let sql = 'select * from chatList where uid=? order by id desc';
    database.query(sql, [uid], (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: '错误！'
        })
        res.send({
            code: 200,
            data: result,
            msg: '查询成功！'
        })
    })
}

module.exports.getArticle = (req, res) => {
    let { uid } = req.body;
    let sql = 'select * from article where uid=? order by id desc';
    database.query(sql, [uid], (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: '错误！'
        })
        res.send({
            code: 200,
            data: result,
            msg: '查询成功！'
        })
    })
}

// 获取模板列表
module.exports.getTemplateList = (req, res) => {
    let sql = 'select id,brief,title from template';
    database.query(sql, (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: '错误！'
        })
        return res.send({
            code: 200,
            msg: '查询成功！',
            data: result
        })
    })
}

// 生成文章
module.exports.makeArticle = (req, res) => {
    let { uid, temid, topic, wordsNumber } = req.body;
    let sql = 'select data from template where id=?';
    database.query(sql, [temid], (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: '错误！'
        })
        if (result.length <= 0) {
            return res.send({
                code: 400,
                msg: '参数错误！'
            })
        }

        let templateData = result[0].data;
        let newArticle = createArticle(templateData, topic, wordsNumber);
        let date = dayjs().format('YYYY-MM-DD hh:mm:ss')

        // 将文章写入到数据库
        let sql = `insert into article (uid,title,content,date,type) values (?,?,?,?,'template')`;
        console.log(sql)
        database.query(sql, [uid, topic, newArticle.article, date], (err1, res1) => {
            if (err1) return res.send({
                code: 400,
                msg: '数据库炸啦！'
            })
            if (res1.affectedRows === 1) {
                newArticle.topic = topic;
                res.send({
                    code: 200,
                    message: '文章生成成功！',
                    data: newArticle
                })
            }
        })


    })
}
module.exports.chat = async(req, res) => {

    let { content, chat_id } = req.query;
    if (content === null || chat_id === null) {
        return res.send({
            code: 400,
            msg: '参数错误！'
        });
    }

    let { data: resGpt } = await axios({
            method: 'post',
            url: config.gptUrl,
            data: qs.stringify({
                chat_id,
                content,
                remark: 'asnull'
            }),
            headers: {
                'Authorization': 'Bearer XYnaQUnmADHFadqZBYrzPBbfDklVuSSY',
                'content-type': 'application/x-www-form-urlencoded'
            }
        })
        // let buff = new Buffer(resGpt.data.content); // 默认用 utf-8 编码格式解释字符串
        // resGpt.data.content = buff.toString('base64');
    res.header("Content-Type", "text/plain;charset=utf-8");
    return res.send(resGpt)
}

module.exports.ai = async(req, res) => {
    let { content, uid, chat_id, type } = req.body;
    let isNew = false;
    if (content === '' || uid === '') return res.send({
        code: 400,
        msg: '参数错误！'
    });
    if (chat_id === 'new') {
        chat_id = chat_id === 'new' ? '' : chat_id;
        isNew = true;
    }
    let date = dayjs().format('YYYY-MM-DD hh:mm:ss');

    let { data: resGpt } = await axios({
        method: 'post',
        url: config.gptUrl,
        data: qs.stringify({
            chat_id,
            content,
            remark: uid
        }),
        headers: {
            'Authorization': 'Bearer XYnaQUnmADHFadqZBYrzPBbfDklVuSSY',
            'content-type': 'application/x-www-form-urlencoded'
        }
    })
    if (resGpt.code === 200) {
        if (type === 'creation') {
            // 将文章写入到数据库
            let sql1 = `insert into article (uid,title,content,date,type) values (?,?,?,?,'ai')`;
            database.query(sql1, [uid, content, resGpt.data.content, date], (err1, res1) => {
                if (err1) return res.send({
                    code: 400,
                    msg: '数据库炸啦！'
                })
                if (res1.affectedRows === 1) {
                    return res.send(resGpt)
                }
            })
        } else if (type === 'chat') {
            // 用户对话记录
            let sql1 = `insert into chatContent (chatid,uid,content,date,type) values (?,?,?,?,'user')`;
            database.query(sql1, [resGpt.data.chat_id, uid, content, date], (err1, res1) => {
                if (err1) return res.send({
                    code: 400,
                    msg: '数据库炸啦！1' + err1
                })
                if (res1.affectedRows === 1) {
                    if (isNew) {
                        let sql0 = `insert into chatList (chatid,uid,content,date) values (?,?,?,?)`;
                        database.query(sql0, [resGpt.data.chat_id, uid, content, date], (err0, res0) => {
                            if (err0) return res.send({
                                code: 400,
                                msg: '数据库炸啦！2' + err0
                            })
                        })
                    }
                    // 将回复写入到数据库
                    let sql2 = `insert into chatContent (chatid,uid,content,date,type) values (?,?,?,?,'gpt')`;
                    database.query(sql2, [resGpt.data.chat_id, uid, resGpt.data.content, date], (err2, res2) => {
                        if (err2) return res.send({
                            code: 400,
                            msg: '数据库炸啦！3'
                        })
                        if (res2.affectedRows === 1) {
                            return res.send(resGpt)
                        }
                    })
                }
            })
        }
    }

}

module.exports.getChat = (req, res) => {
    let { chat_id } = req.body;
    let sql = 'select * from chatContent where chatid=?';
    database.query(sql, [chat_id], (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: '错误！'
        })
        res.send({
            code: 200,
            data: result,
            msg: '查询成功！'
        })
    })
}

// 文章生成算法
function createArticle(templateData, topic, worldNumber) {
    if (typeof(templateData) == 'string') {
        var json = templateData;
        json = json.replace(/\n/g, "").replace(/\r/g, ""); //去掉字符串中的换行符
        json = json.replace(/\n/g, "").replace(/\s|\xA0/g, ""); //去掉字符串中的所有空格
        try {
            var templateData = JSON.parse(json);
        } catch (e) {
            let lastIndex = templateData.lastIndexOf(',')
            if (lastIndex != -1) {
                let begin = templateData.substring(0, lastIndex);
                let end = templateData.substring(lastIndex + 1);
                var templateData = JSON.parse(begin + end);
            }
        }
    }
    if (!templateData.footers) { templateData.footers = ['']; }
    if (!templateData.headers) { templateData.headers = ['']; }
    var number = 0;
    let headerDataArr = templateData.headers;
    let headerIndex = getRandomIntInclusive(0, headerDataArr.length - 1)
    var header = headerDataArr[headerIndex];
    var number = header.replaceAll(' ', '').length;
    let footerDataArr = templateData.footers;
    let footerIndex = getRandomIntInclusive(0, footerDataArr.length - 1)
    var footer = footerDataArr[footerIndex];
    var number = footer.replaceAll(' ', '').length + number;
    let middleDataArr = templateData.middles;
    var middle = '';
    while (true) {
        let middleIndex = getRandomIntInclusive(0, middleDataArr.length - 1)
        let middleItem = middleDataArr[middleIndex]
        var number = number + middleItem.replaceAll(' ', '').replaceAll('\n\n&emsp;&emsp;', '').length;
        var middle = middle + '\n\n&emsp;&emsp;' + middleItem;
        if (number + 50 > worldNumber) {
            break;
        }
    }
    var article = header + middle + '\n\n&emsp;&emsp;' + footer;
    var article = article.replaceAll('x', topic) + '\n\n[声明：本文由智能创作助手生成]';
    return {
        article,
        actualNumber: number
    }
}

// 生成随机整数数
function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值
}